﻿using Microsoft.AspNetCore.Mvc.ApplicationModels;
using XYS.Core.Api.Attributes;

namespace XYS.Service.Core.Util.Conventions;

/// <summary>
/// 检查控制器的OpenApiInfo特性并设置对应的GroupName
/// </summary>
public class ControllerModelConvention : IControllerModelConvention
{
    /// <summary>
    /// 
    /// </summary>
    public void Apply(ControllerModel controller)
    {
        //自动处理 ApiExplorerModel 特性
        ApplyApiExplorerModel(controller);
    }


    /// <summary>
    /// 自动处理 ApiExplorerModel 特性
    /// </summary>
    /// <param name="controller"></param>
    private void ApplyApiExplorerModel(ControllerModel controller)
    {
        // 获取控制器上的OpenApiInfo特性
        var openApiInfo = controller.Attributes
            .OfType<OpenApiInfoAttribute>()
            .FirstOrDefault();
        if (openApiInfo == null) return;

        // 确保ApiExplorer模型存在
        controller.ApiExplorer ??= new ApiExplorerModel();
        // 设置GroupName为OpenApiInfo的GroupName属性
        controller.ApiExplorer.GroupName = openApiInfo.Name;
    }


}
